package com.conjane.algo.linked_list;

/**
 * 单向链表
 */
public class JLinkedList<E> {

    private Node<E> head = null;

    private int size = 0;

    public void add(E e){
        Node<E> node = new Node<>(e);
        if (head == null){
            head = new Node<>();
            head.next = node;
        }else {
            Node<E> temp = head;
            while (temp.next != null){
                temp = temp.next;
            }
            temp.next = node;
        }
        size++;
    }

    public Node<E> get(int index){
        if (head.next == null){
            return null;
        }
        Node<E> temp = head;
        for (int i = 0; i <= index; i++) {
            temp = temp.next;
        }
        return temp;
    }

    public Integer size(){
        return this.size;
    }

    @Override
    public String toString() {
        Node<E> temp = head;
        StringBuilder builder = new StringBuilder();
        while (temp.next != null){
            temp = temp.next;
            builder.append(temp.val).append("->");
        }
        builder.append("null");
        return builder.toString();
    }

    private static class Node<E> {
        E val;
        Node<E> next;
        Node(){}
        Node(E val){
            this.val = val;
        }
        Node(E val,Node<E> next){
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        JLinkedList<Integer> linkedList = new JLinkedList<>();
        linkedList.add(1);
        linkedList.add(2);
        linkedList.add(3);
        linkedList.add(4);
        System.out.println(linkedList);
        System.out.println(linkedList.size());
        System.out.println(linkedList.get(2).val);
    }
}
